<template>
  <ScenicScreen
    v-model="list.filter.scenicId"
    @change="selectScenic"
    :isAll="false"
  >
    <div class="app-container">
      <el-form
        ref="listFilterRef"
        :model="list.filter"
        inline
        class="list-filter"
      >
        <el-form-item prop="keyword">
          <el-input
            v-model="list.filter.keyword"
            placeholder="路线名称"
            style="width:200px"
            clearable
          >
            <i slot="prefix" class="el-input__icon el-icon-search" />
          </el-input>
        </el-form-item>
        <el-button @click="reset">重置</el-button>
      </el-form>

      <div class="table-operation">
        <el-button
          v-if="hasBtn['新增']"
          type="primary"
          icon="el-icon-circle-plus-outline"
          @click="
            () => {
              c()
              window.setTimeout(() => {
                if ($refs.MapPreview.map) {
                  preview()
                }
              }, 2)
            }
          "
        >
          新增
        </el-button>
      </div>

      <el-table v-loading="list.loading" :data="list.data" v-bind="tableProp">
        <el-table-column label="路线名称" prop="routeName" />
        <el-table-column label="点位数量" prop="spotNumber" />
        <el-table-column label="排序值" prop="routeSort" />
        <el-table-column label="状态" align="center">
          <template slot-scope="{ row: { routeId, status } }">
            <KiPopSwitch
              v-bind="popSwitchProps(status)"
              @change="updateStatus({ id: routeId, status: status ^ 1 })"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="{ row: { routeId } }">
            <KiPopButton
              v-if="hasBtn['查看']"
              @click="r({ id: routeId }, 'config')"
            >
              查看
            </KiPopButton>
            <KiPopButton
              v-if="hasBtn['编辑']"
              @click="u({ id: routeId }, 'config')"
            >
              编辑
            </KiPopButton>
            <KiPopButton
              v-if="hasBtn['删除']" text="![#FF7575]"
              :elPopconfirmProps="{ title: '确认删除吗？' }"
              @click="d({ id: routeId })"
            >
              删除
            </KiPopButton>
          </template>
        </el-table-column>
      </el-table>

      <KiFormDialog
        :show.sync="form.show"
        :title="formTitle"
        v-model="form.data"
        :submit="submit"
        :readonly="form.status === 'r'"
        ref="formRef"
        :loading="form.loading"
      >
        <template #el-form>
          <el-form-item label="路线名称" prop="routeName" verify>
            <el-input
              v-model="form.data.routeName"
              placeholder="请输入路线名称"
              maxlength="30"
              show-word-limit
              clearable
            />
          </el-form-item>
          <el-form-item label="预计游玩时长" prop="estimatedTime" verify>
            <Sort
              v-model="form.data.estimatedTime"
              :max="200"
              placeholder="请输入预计游玩时长"
            />
          </el-form-item>
          <el-form-item label="排序值" prop="routeSort" verify>
            <Sort v-model="form.data.routeSort" />
          </el-form-item>
          <el-form-item label="选择路线点位" prop="routeSpots" verify>
            <el-table :data="form.data.routeSpots" border fit stripe>
              <el-table-column label="类型" width="180">
                <template slot-scope="scope">
                  <KiSelect
                    v-model="scope.row.spotType"
                    :options="dict.spot_type"
                    @change="changeSpotType(scope)"
                  />
                </template>
              </el-table-column>
              <el-table-column label="点位" width="180">
                <template slot-scope="{ row, $index }">
                  <el-form-item verify>
                    <KiSelect
                      v-model="row.__spot"
                      :options="row.__spotOption"
                      value-key="id"
                      :props="{ value: '', label: 'name' }"
                      @change="changeSpot($event, $index)"
                      placeholder="请先选择类型"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="是否连接">
                <template slot-scope="{ row }">
                  <el-switch
                    v-model="row.connected"
                    :active-value="1"
                    :inactive-value="0"
                    active-color="#13ce66"
                  ></el-switch>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                  <el-button
                    type="danger"
                    circle
                    icon="el-icon-delete"
                    @click="form.data.routeSpots.splice(scope.$index, 1)"
                  />
                </template>
              </el-table-column>
            </el-table>
            <el-button-group style="width:100%">
              <el-button
                style="width:50%"
                icon="el-icon-circle-plus-outline"
                @click="addSpot"
              />
              <el-button
                style="width:50%"
                type="primary"
                @click="manualPreview"
              >
                生成
              </el-button>
            </el-button-group>
          </el-form-item>
          <MapPreview
            v-if="$refs.formRef && !$refs.formRef.Loading"
            :data="mapPreview"
            ref="MapPreview"
            @refreshMapPreviewData="refreshMapPreviewData"
          />
        </template>
      </KiFormDialog>
    </div>
  </ScenicScreen>
</template>

<script>
import MapPreview from './MapPreview'
import pageMixin from '@/utils/pageMixin'
import useAdmateAdapter from '@/utils/useAdmateAdapter'
import ScenicScreen from '@/components/ScenicScreen'

export default {
  mixins: [pageMixin],
  components: { MapPreview, ScenicScreen },
  setup: () =>
    useAdmateAdapter({
      urlPrefix: 'sot-admin-api/scenic/route',
      axiosConfig: {
        getList: {
          url: 'list'
        },
        d: {
          method: 'DELETE'
        },
        r: ({ id }) => ({
          url: 'queryInfoById/' + id,
          method: 'GET'
        })
      },
      form: {
        data: {
          routeSpots: [
            { __spotOption: [], connected: 1 },
            { __spotOption: [], connected: 1 }
          ],
          __generatedRouteSpots: []
        }
      }
    }, {
      afterRetrieve(res) {
        if (res.data.routeSpots) {
          for (let i = 0; i < res.data.routeSpots.length; i++) {
            this.form.data.routeSpots[i].__spotOption = []
            this.form.data.routeSpots[i].__spot = {
              id: res.data.routeSpots[i].spotId,
              latitude: res.data.routeSpots[i].latitude,
              longitude: res.data.routeSpots[i].longitude
            }
            this.changeSpotType({ row: res.data.routeSpots[i], $index: i })
          }
        }
        this.mapPreview.routePath = res.data.routePath
        this.mapPreview.spot = res.data.routeSpots.filter(v => v.spotId)
        this.form.data.__generatedRouteSpots = this.$lo.cloneDeep(
          res.data.routeSpots
        )
        this.generated = true
      },
    }),
  data () {
    return {
      window,
      generated: false,
      mapPreview: {
        center: [],
        spot: [],
        path: []
      }
    }
  },
  watch: {
    'form.data.routeSpots': {
      deep: true,
      handler (newVal) {
        //注意：在变异 (不是替换) 对象或数组时，旧值将与新值相同，因为它们的引用指向同一个对象/数组。Vue 不会保留变异之前值的副本。
        if (
          !this.$lo.isEqualWith(
            newVal,
            this.form.data.__generatedRouteSpots,
            (objValue, othValue) => {
              if (
                this.$lo.isPlainObject(objValue) &&
                this.$lo.isPlainObject(othValue) &&
                objValue.spotId === othValue.spotId &&
                objValue.connected === othValue.connected
              ) {
                return true
              }
            }
          )
        ) {
          this.generated = false
        }
      }
    },
    'form.show' (newVal) {
      if (!newVal) {
        this.mapPreview.spot = []
        this.mapPreview.path = []
        this.mapPreview.routePath = []
      }
    }
  },
  methods: {
    preview () {
      this.mapPreview.spot = this.form.data.routeSpots.filter(v => v.spotId)
      this.mapPreview.path = this.mapPreview.spot.filter(v => v.connected === 1)
      this.$refs.MapPreview.renderImg()
      this.$refs.MapPreview.renderMarker()
      this.$refs.MapPreview.renderPath()
    },
    submit () {
      if (this.generated) {
        if (this.form.status === 'c') {
          this.form.data.scenicId = this.list.filter.scenicId
        }
        return this.submitForm()
      } else {
        this.$swal.warning('请先生成路线')
        return { show: true, }
      }
    },
    selectScenic (scenicId, scenicItem) {
      this.mapPreview.location = []
      this.mapPreview.mapPath = ''
      this.mapPreview.center = [scenicItem.latitude, scenicItem.longitude]
      if (scenicItem['mapId']) {
        this.$POST(
          'sot-admin-api/scenic/map/queryMapInfoById/' + res.data['mapId']
        ).then(res => {
          this.mapPreview.location = res.data.location
          this.mapPreview.mapPath = res.data.mapPath
        })
      }

      this.getList()
    },
    refreshMapPreviewData (e) {
      this.form.data = {
        ...this.form.data,
        ...e
      }
      this.form.data.__generatedRouteSpots = this.$lo.cloneDeep(
        this.form.data.routeSpots
      )
      this.generated = true
    },
    changeSpotType ({ row, $index }) {
      if (this.form.data.routeSpots[$index]) {
        this.form.data.routeSpots[$index].__spotOption = []
      }
      if (row.spotType) {
        this.$POST('sot-admin-api/scenic/spot/listForSelect', {
          spotType: row.spotType,
          scenicId: this.list.filter.scenicId,
          status: 1
        }).then(res => {
          this.form.data.routeSpots[$index].__spotOption = res.data
        })
      }
    },
    changeSpot (e, i) {
      if (e) {
        this.form.data.routeSpots[i].spotId = e.id
        this.form.data.routeSpots[i].longitude = e.longitude
        this.form.data.routeSpots[i].latitude = e.latitude
      }
    },
    manualPreview () {
      if (
        this.form.data.routeSpots?.filter(v => v.connected === 1 && v.spotId)
          .length > 1
      ) {
        this.preview()
      } else {
        this.$swal.warning('至少添加两个点位')
      }
    },
    addSpot () {
      if (this.form.data.routeSpots.length >= 20) {
        this.$swal.warning('最多20个点位')
      } else {
        this.form.data.routeSpots.push({
          __spot: {},
          connected: 1,
          __spotOption: []
        })
      }
    }
  }
}
</script>

<style scoped lang="scss">
.p-20px {
  & :deep(.el-menu) {
    overflow-y: scroll;
  }
}
</style>
